/*****************************************************************************
* Project:
* All project
* Copyright(C) 2020-2021 Shenju Co.Ltd, All rights reserved.
* Description:
* All code is genrated by yangyang
* Author:
* yangyang
****************************************************************************/
#include "oal_timer.h"

#include <Windows.h>

typedef struct {
	DWORD time;
	OAL_TIMER_ROUTINE pfunc;
	HANDLE threadHandle;
	void *user_arg;
	OAL_TIMER_ACTIVATE active;
}_TIMER_PARA;


DWORD CALLBACK ThreadProc(PVOID pvoid)
{
	_TIMER_PARA *_this = pvoid;

	while (1)
	{
		Sleep(_this->time);
		if(_this->active == OAL_TIMER_AUTO_ACTIVATE)
			_this->pfunc(_this->user_arg);
	}
}

int OAL_timer_create(OAL_TIMER* timer_t, const char* name, int ticks,
	OAL_TIMER_ROUTINE pfunc, void* cb_arg,
	OAL_TIMER_RELOAD reload, OAL_TIMER_ACTIVATE activate)
{
	name = name;
	reload = reload;
	DWORD dwThreadId;
	_TIMER_PARA *_this = calloc(1, sizeof(_TIMER_PARA));
	if (_this)
	{
		_this->pfunc = pfunc;
		_this->time = ticks;
		_this->user_arg = cb_arg;
		_this->active = activate;
		_this->threadHandle = CreateThread(0, 0, ThreadProc, _this, 0, &dwThreadId);
	}

	*timer_t = _this;

	return OAL_SUCCESS;
}

int OAL_timer_activate(OAL_TIMER* timer_t, OAL_TIMER_ACTIVATE activate)
{
	_TIMER_PARA *_this = (_TIMER_PARA *)*timer_t;
	_this->active = activate;
	return OAL_SUCCESS;
}

int OAL_timer_delete(OAL_TIMER* timer_t)
{
	_TIMER_PARA *_this = (_TIMER_PARA *)*timer_t;

	if (_this)
	{
		TerminateThread(_this->threadHandle, 0);
		free(_this);
	}

	return OAL_SUCCESS;
}

